<script lang="tsx">
import { defineComponent } from 'vue';
import { h } from 'vue';
import { baseTablePage } from '@shensi/ui';
import { ElMessage, ElTag } from 'element-plus';
import { Page } from '@vben/common-ui';

export default defineComponent({
  name: 'Test1',
  setup() {
    // 模拟 API
    const createMockAPI = () => ({
      get: async (params: any) => {
        console.log('查询参数:', params);
        await new Promise(resolve => setTimeout(resolve, 800));

        const mockUsers = [
          { id: 1, username: 'admin', email: 'admin@example.com', role: 'admin', status: 1, lastLogin: '2024-01-20 09:30:00' },
          { id: 2, username: 'editor', email: 'editor@example.com', role: 'editor', status: 1, lastLogin: '2024-01-19 14:20:00' },
          { id: 3, username: 'viewer', email: 'viewer@example.com', role: 'viewer', status: 0, lastLogin: '2024-01-18 16:45:00' },
          { id: 4, username: 'test001', email: 'test001@example.com', role: 'editor', status: 1, lastLogin: '2024-01-17 11:15:00' },
          { id: 5, username: 'test002', email: 'test002@example.com', role: 'viewer', status: 1, lastLogin: '2024-01-16 08:30:00' },
        ];

        const { page = 1, size = 10, username = '', role = '' } = params;
        let filtered = mockUsers;

        if (username) {
          filtered = filtered.filter(u => u.username.includes(username) || u.email.includes(username));
        }
        if (role) {
          filtered = filtered.filter(u => u.role === role);
        }

        const start = (page - 1) * size;
        const data = filtered.slice(start, start + size);

        return { data, total: filtered.length };
      },

      post: async (data: any) => {
        console.log('新增用户:', data);
        await new Promise(resolve => setTimeout(resolve, 500));
        ElMessage.success('用户创建成功');
      },

      put: async (data: any) => {
        console.log('更新用户:', data);
        await new Promise(resolve => setTimeout(resolve, 500));
        ElMessage.success('用户更新成功');
      },

      delete: async (data: any) => {
        console.log('删除用户:', data);
        await new Promise(resolve => setTimeout(resolve, 500));
        ElMessage.success('用户删除成功');
      },
    });

    // 列配置
    const userColumns = [
      {
        prop: 'id',
        label: 'ID',
        width: 80,
        hideTypes: ['post', 'put'], // 新增和编辑时隐藏
      },
      {
        prop: 'username',
        label: '用户名',
        minWidth: 120,
        type: 'input',
        required: true,
        placeholder: '请输入用户名',
        rules: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' },
        ],
      },
      {
        prop: 'email',
        label: '邮箱',
        minWidth: 200,
        type: 'input',
        required: true,
        placeholder: '请输入邮箱',
        rules: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
        ],
      },
      {
        prop: 'role',
        label: '角色',
        width: 120,
        type: 'select',
        required: true,
        placeholder: '请选择角色',
        options: [
          { label: '管理员', value: 'admin' },
          { label: '编辑者', value: 'editor' },
          { label: '查看者', value: 'viewer' },
        ],
        render: (row: any) => {
          const roleMap = {
            admin: { text: '管理员', type: 'danger' },
            editor: { text: '编辑者', type: 'warning' },
            viewer: { text: '查看者', type: 'info' },
          };
          const role = roleMap[row.role as keyof typeof roleMap];
          return h(ElTag, { type: role?.type as any }, () => role?.text);
        },
      },
      {
        prop: 'status',
        label: '状态',
        width: 100,
        type: 'radio',
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
        render: (row: any) => {
          return h(ElTag, {
            type: row.status === 1 ? 'success' : 'danger',
          }, () => row.status === 1 ? '启用' : '禁用');
        },
      },
      {
        prop: 'lastLogin',
        label: '最后登录',
        width: 160,
        hideTypes: ['post', 'put'], // 新增和编辑时隐藏
      },
      {
        prop: 'password',
        label: '密码',
        type: 'password',
        placeholder: '请输入密码',
        hideTypes: ['view'], // 查看时隐藏
        disabledTypes: ['put'], // 编辑时禁用
        rules: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        ],
        // 在表格中不显示
        width: 0,
        render: () => '******',
      },
    ];

    // 查询配置
    const queryConfig = [
      {
        prop: 'username',
        label: '用户名/邮箱',
        type: 'input',
        placeholder: '请输入用户名或邮箱',
      },
      {
        prop: 'role',
        label: '角色',
        type: 'select',
        placeholder: '请选择角色',
        options: [
          { label: '全部', value: '' },
          { label: '管理员', value: 'admin' },
          { label: '编辑者', value: 'editor' },
          { label: '查看者', value: 'viewer' },
        ],
      },
    ];

    // 操作按钮配置
    const operationCommands = [
      {
        label: '查看',
        key: 'view',
        type: 'info',
        size: 'small',
      },
      {
        label: '编辑',
        key: 'put',
        type: 'primary',
        size: 'small',
        // icon: Edit,
      },
      {
        label: '删除',
        key: 'delete',
        type: 'danger',
        size: 'small',
        // icon: Delete,
      },
    ];

    // 自定义操作处理
    const handleCustomCommand = (type: string, data?: any, index?: number) => {
      console.log('自定义操作:', { type, data, index });

      switch (type) {
        case 'export':
          ElMessage.success('导出用户数据');
          break;
        case 'import':
          ElMessage.success('导入用户数据');
          break;
        case 'resetPassword':
          ElMessage.success(`重置用户 ${data?.username} 的密码`);
          break;
        default:
          ElMessage.info(`执行操作: ${type}`);
      }
    };

    // 自定义头部按钮
    const customHeaderButtons = () => (
      <div class="flex gap-2">
        <el-button
          type="success"
          // icon={Download}
          onClick={() => handleCustomCommand('export')}
        >
          导出数据
        </el-button>
        <el-button
          type="warning"
          // icon={Upload}
          onClick={() => handleCustomCommand('import')}
        >
          导入数据
        </el-button>
      </div>
    );

    // 创建页面实例
    const { render } = baseTablePage({
      pageClass: ['user-management-page'],
      API: createMockAPI(),
      columns: userColumns,
      queryColumns: queryConfig,
      commands: operationCommands,
      query: {
        username: '',
        role: '',
      },
      prefix: customHeaderButtons, // 自定义头部按钮
      deleteProps: {
        message: '确定要删除该用户吗？删除后不可恢复！',
        title: '删除用户',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
      },
      handleCommand: handleCustomCommand,
    });

    return () => <Page class="question h-full">
      <div class="question-bank flex flex-col h-full bg-[#fff] p-4">
        {render({ header: <div></div> })}
      </div>
    </Page>;
  },
});
</script>
